import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:path/path.dart' as path;
import 'services/config_service.dart';
import 'models/unified_config.dart';

class ConfigImportExportService {
  static const String configFileExtension = '.nuitka_config';

  /// 导出配置到文件
  static Future<bool> exportConfig(BuildContext context) async {
    try {
      // 获取当前配置
      final configService = await ConfigService.getInstance();
      final config = await configService.loadUnifiedConfig();

      // 转换为JSON
      final configJson = {
        'version': '1.0.0',
        'exportTime': DateTime.now().toIso8601String(),
        'config': config.toJson(),
      };

      // 选择保存位置
      String? outputFile = await FilePicker.platform.saveFile(
        dialogTitle: '导出Nuitka配置',
        fileName:
            'nuitka_config_${DateTime.now().millisecondsSinceEpoch}$configFileExtension',
        type: FileType.custom,
        allowedExtensions: ['nuitka_config'],
      );

      if (outputFile != null) {
        // 确保文件扩展名正确
        if (!outputFile.endsWith(configFileExtension)) {
          outputFile += configFileExtension;
        }

        // 写入文件
        final file = File(outputFile);
        await file.writeAsString(
          const JsonEncoder.withIndent('  ').convert(configJson),
          encoding: utf8,
        );

        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('配置已导出到：${path.basename(outputFile)}'),
              backgroundColor: Colors.green,
              duration: const Duration(seconds: 3),
            ),
          );
        }

        return true;
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导出失败：$e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }

    return false;
  }

  /// 从文件导入配置
  static Future<bool> importConfig(BuildContext context) async {
    try {
      // 选择配置文件
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['nuitka_config', 'json'],
        dialogTitle: '选择Nuitka配置文件',
      );

      if (result != null && result.files.single.path != null) {
        final file = File(result.files.single.path!);

        // 读取文件内容
        final content = await file.readAsString(encoding: utf8);
        final jsonData = jsonDecode(content);

        // 验证配置文件格式
        if (!_validateConfigFile(jsonData)) {
          throw Exception('无效的配置文件格式');
        }

        // 显示确认对话框
        if (context.mounted) {
          final confirmed = await _showImportConfirmDialog(
            context,
            jsonData,
            path.basename(file.path),
          );

          if (confirmed == true) {
            // 导入配置
            final configData = jsonData['config'] as Map<String, dynamic>;
            final config = UnifiedConfig.fromJson(configData);

            // 保存配置
            final configService = await ConfigService.getInstance();
            await configService.saveUnifiedConfig(config);

            if (context.mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('配置导入成功！'),
                  backgroundColor: Colors.green,
                  duration: Duration(seconds: 3),
                ),
              );
            }

            return true;
          }
        }
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('导入失败：$e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }

    return false;
  }

  /// 验证配置文件格式
  static bool _validateConfigFile(Map<String, dynamic> jsonData) {
    return jsonData.containsKey('config') &&
        jsonData['config'] is Map<String, dynamic>;
  }

  /// 显示导入确认对话框
  static Future<bool?> _showImportConfirmDialog(
    BuildContext context,
    Map<String, dynamic> jsonData,
    String fileName,
  ) {
    final exportTime = jsonData['exportTime'] as String?;
    final version = jsonData['version'] as String?;

    return showDialog<bool>(
      context: context,
      builder: (BuildContext context) {
        final theme = Theme.of(context);

        return AlertDialog(
          title: Row(
            children: [
              Icon(Icons.file_download, color: theme.colorScheme.primary),
              const SizedBox(width: 8),
              const Text('导入配置确认'),
            ],
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('确定要导入以下配置文件吗？'),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: theme.colorScheme.surfaceVariant.withOpacity(0.3),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildInfoRow('文件名', fileName),
                    if (version != null) _buildInfoRow('版本', version),
                    if (exportTime != null)
                      _buildInfoRow('导出时间', _formatDateTime(exportTime)),
                  ],
                ),
              ),
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.orange.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(6),
                  border: Border.all(color: Colors.orange.withOpacity(0.3)),
                ),
                child: Row(
                  children: [
                    Icon(Icons.warning, color: Colors.orange, size: 16),
                    const SizedBox(width: 6),
                    Expanded(
                      child: Text(
                        '导入将覆盖当前所有配置',
                        style: TextStyle(
                          color: Colors.orange.shade700,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('确认导入'),
            ),
          ],
        );
      },
    );
  }

  /// 构建信息行
  static Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 60,
            child: Text(
              '$label：',
              style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 12),
            ),
          ),
          Expanded(child: Text(value, style: const TextStyle(fontSize: 12))),
        ],
      ),
    );
  }

  /// 格式化日期时间
  static String _formatDateTime(String isoString) {
    try {
      final dateTime = DateTime.parse(isoString);
      return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} '
          '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    } catch (e) {
      return isoString;
    }
  }

  /// 获取配置存储位置信息
  static String getConfigStorageInfo() {
    return '''配置存储位置：
• 本地存储：使用SharedPreferences存储在系统注册表中
• Windows路径：HKEY_CURRENT_USER\\Software\\flutter.nuitkaapp
• 导出文件：可保存为 .nuitka_config 文件便于备份和分享
• 支持格式：JSON格式，包含完整的项目配置信息''';
  }
}
